<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <script>
    function setHandler() {
      window.onbeforeunload = function() {
        return "There are unsaved changes. Leave now?";
      };
    }
  </script>

  <button onclick="setHandler()">Set window.onbeforeunload</button>

  <a href="http://example.com">Leave for EXAMPLE.COM</a>
</body>
</html>
